package com.example.carrierapp.ui.main.find;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.carrierapp.base.MVPBaseFragment;
import com.example.carrierapp.bean.find.FindGoodsListBean;
import com.example.carrierapp.event.GoodsRefreshEvent;
import com.example.carrierapp.ui.adapter.FindGoodsAdatpter;
import com.example.carrierapp.ui.dialog.DialogUtils;
import com.example.carrierapp.ui.pop.CitySelectPopup;
import com.example.carrierapp.ui.view.recycleview.HorizontalDividerDecoration;
import com.example.carrierapp.ui.view.recycleview.WrapContentManager;
import com.example.carrierapp.ui.view.recycleview.XRecyclerView;
import com.example.carrierapp.util.ActivityUtil;
import com.example.carrierapp.util.ConnectionUtil;
import com.example.carrierapp.util.DisplayUtil;
import com.example.carrierapp.util.LogUtil;
import com.example.carrierapp.util.ToastUtils;
import com.example.lb.fingerdemo.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 找货 列表
 */
public class FindGoodsFragment extends MVPBaseFragment<FindGoodsContract.View, FindGoodsPresenter> implements FindGoodsContract.View, XRecyclerView.LoadingListener, FindGoodsAdatpter.OnBtnClickListener {
    private static final int TIME_STATE_3 = 3;
    private static final int TIME_STATE_0 = 0;
    private static final int TIME_STATE_7 = 7;
    @BindView(R.id.rl_incar_address)
    RelativeLayout mRlIncar;
    @BindView(R.id.rl_outcar_address)
    RelativeLayout mRlOut;
    @BindView(R.id.rl_new)
    RelativeLayout mRlNew;

    @BindView(R.id.tv_incar_address)
    TextView mTvIncar;
    @BindView(R.id.tv_outcar_address)
    TextView mTvOut;
    @BindView(R.id.tv_new)
    TextView mTvNew;

    @BindView(R.id.ll_empty)
    LinearLayout mEmptyView;

    @BindView(R.id.recycler_view)
    XRecyclerView mRecyclerView;
    private Drawable mDrawableDown;
    private Drawable mDrawableUp;

    private int mPage = 0;
    private String mLoadAddress = "";
    private String mUnLoadAddress = "";
    private int mTimeState = TIME_STATE_0;
    private boolean mLoadMore;
    private FindGoodsAdatpter mAdapter;
    private CitySelectPopup mCitySelectPopup;
    private PopupWindow mTimePopWindow;
    private LayoutInflater mLayoutInflater;

    public static Fragment newInstance() {
        FindGoodsFragment tenderFragment = new FindGoodsFragment();
        return tenderFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void initView() {
        super.initView();
        ButterKnife.bind(this, mRootView);
        initRecycleView();
    }

    @Override
    public void initData() {
        super.initData();
        showProgress();
        mPresenter.attachView(this);
        mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
    }

    private void initRecycleView() {
        WrapContentManager mLinearLayoutManager = new WrapContentManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.addItemDecoration(new HorizontalDividerDecoration(getContext(), R.drawable.divider_horizontal_2_f3f6fa, DisplayUtil.dip2px(getContext(), 10)));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLoadingMoreEnabled(true);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingListener(this);
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();

        mAdapter = new FindGoodsAdatpter();
        mAdapter.setOnBtnClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    @OnClick({R.id.rl_incar_address, R.id.rl_outcar_address, R.id.rl_new})
    public void onTopClick(View v) {
        if (mDrawableDown == null) {
            mDrawableDown = getResources().getDrawable(R.drawable.icon_drop_down);
        }
        if (mDrawableUp == null) {
            mDrawableUp = getResources().getDrawable(R.drawable.icon_upward);
        }
        switch (v.getId()) {
            case R.id.rl_incar_address:
                showIncarAddress(v);

                mRlIncar.setBackgroundResource(R.drawable.icon_select_zone);
                mRlOut.setBackground(null);
                mRlNew.setBackground(null);
                mTvIncar.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableUp, null);
                mTvOut.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableDown, null);
                mTvNew.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableDown, null);
                mTvIncar.setTextColor(Color.parseColor("#222222"));
                mTvOut.setTextColor(Color.parseColor("#ffffff"));
                mTvNew.setTextColor(Color.parseColor("#ffffff"));
                break;
            case R.id.rl_outcar_address:
                showOutCarAddress(v);
                mRlOut.setBackgroundResource(R.drawable.icon_select_zone);
                mRlIncar.setBackground(null);
                mRlNew.setBackground(null);
                mTvOut.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableUp, null);
                mTvIncar.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableDown, null);
                mTvNew.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableDown, null);
                mTvOut.setTextColor(Color.parseColor("#222222"));
                mTvIncar.setTextColor(Color.parseColor("#ffffff"));
                mTvNew.setTextColor(Color.parseColor("#ffffff"));
                break;
            case R.id.rl_new:
                showTimePop(v);
                mRlNew.setBackgroundResource(R.drawable.icon_select_zone);
                mRlOut.setBackground(null);
                mRlIncar.setBackground(null);
                mTvNew.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableUp, null);
                mTvIncar.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableDown, null);
                mTvOut.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawableDown, null);
                mTvNew.setTextColor(Color.parseColor("#222222"));
                mTvIncar.setTextColor(Color.parseColor("#ffffff"));
                mTvOut.setTextColor(Color.parseColor("#ffffff"));
                break;
        }
    }

    private void showTimePop(View timeView) {
        if (mTimePopWindow == null) {
            if (mLayoutInflater == null) {
                mLayoutInflater = LayoutInflater.from(getContext());
            }
            View view = mLayoutInflater.inflate(R.layout.layout_find_time_type, null);
            view.findViewById(R.id.tv_time_0).setOnClickListener(v -> {
                mTimePopWindow.dismiss();
                mTvNew.setText("最新");
                mTimeState = TIME_STATE_0;
                mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
            });
            view.findViewById(R.id.tv_time_3).setOnClickListener(v -> {
                mTimePopWindow.dismiss();
                mTvNew.setText("最近三天");
                mTimeState = TIME_STATE_3;
                mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
            });
            view.findViewById(R.id.tv_time_7).setOnClickListener(v -> {
                mTimePopWindow.dismiss();
                mTvNew.setText("最近一周");
                mTimeState = TIME_STATE_7;
                mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
            });
            mTimePopWindow = new PopupWindow(view, DisplayUtil.dip2px(getContext(), 125), DisplayUtil.dip2px(getContext(), 110), true);
            mTimePopWindow.setOutsideTouchable(true);
        }
        mTimePopWindow.showAsDropDown(timeView);
    }

    private void showIncarAddress(View v) {
        mCitySelectPopup = new CitySelectPopup(getActivity(), getContext(), null, 0);
        mCitySelectPopup.showInParentDown(v);
        mCitySelectPopup.setCityChooserListener((cityName, id) -> {
            mLoadAddress = cityName;
            mTvIncar.setText(cityName);
            mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
        });
    }

    private void showOutCarAddress(View v) {
        mCitySelectPopup = new CitySelectPopup(getActivity(), getContext(), null, 0);
        mCitySelectPopup.showInParentDown(v);
        mCitySelectPopup.setCityChooserListener((cityName, id) -> {
            mTvOut.setText(cityName);
            mUnLoadAddress = cityName;
            mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
        });
    }


    @Override
    protected int getLayout() {
        return R.layout.fragment_findgoods;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onListRefresh(GoodsRefreshEvent event) {
        LogUtil.d("FindGoodsFragment-onListRefresh");
        onRefresh();
    }

    @Override
    protected FindGoodsPresenter createPresenter() {
        return new FindGoodsPresenter(getContext());
    }

    @Override
    public void getFindGoodsListSuccess(FindGoodsListBean bean) {
        dismissProgress();
        LogUtil.d("FindGoodsFragment-getFindGoodsListSuccess-" + bean);
        if (mRecyclerView != null) {
            mRecyclerView.loadMoreComplete();
            mRecyclerView.refreshComplete();
        }
        List<FindGoodsListBean.DispatchInfo> list = bean.getItems();
        LogUtil.d("FindGoodsFragment-getFindGoodsListSuccess-" + list.size());
        if (!ConnectionUtil.isNull(list)) {
            mEmptyView.setVisibility(View.GONE);
            if (mLoadMore) {
                mLoadMore = false;
                mAdapter.addDataNotClear(list);
            } else {
                mAdapter.addData(list);
            }
            if (mRecyclerView != null && list.size() < 10) {
                mRecyclerView.setNoMore(true);
            } else {
                mRecyclerView.setNoMore(false);
            }
        } else {
            mRecyclerView.setNoMore(true);
            if (!mLoadMore) {
                mAdapter.clear();
                mEmptyView.setVisibility(View.VISIBLE);
            } else {
                mEmptyView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void getFindGoodsListFailde(String msg) {
        dismissProgress();
        LogUtil.d("FindGoodsFragment-getFindGoodsListFailde-" + msg);
        ToastUtils.showCenterToast(msg, getContext());
        if (mRecyclerView != null) {
            mRecyclerView.loadMoreComplete();
            mRecyclerView.refreshComplete();
        }
        mEmptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onRefresh() {
        mTvIncar.setText("装车地");
        mTvOut.setText("卸货地");
        mTvNew.setText("最新");
        mPage = 0;
        mLoadMore = false;
        mLoadAddress = "";
        mUnLoadAddress = "";
        mTimeState = TIME_STATE_0;
        mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
    }

    @Override
    public void onLoadMore() {
        mLoadMore = true;
        mPage++;
        mPresenter.getFindGoodsList(mLoadAddress, mUnLoadAddress, mTimeState, mPage);
    }

    @Override
    public void onDetailClick(FindGoodsListBean.DispatchInfo info) {
        if (info.isGroup) {
            new DialogUtils.Builder(getContext())
                    .setMessage("多线运输招标暂时只能在电脑进行操作，非常抱歉！")
                    .setOutTouch(false)
                    .setOnlyPositive()
                    .creat().show();
        } else {
            ActivityUtil.startFindDetail(getContext(), info.id, info.paidModel);
        }

    }
}
